package bma.common.langutil.core;

import java.text.MessageFormat;

/**
 * 大小工具类
 * 
 * @author 关中
 * @since 1.0 (imported from BMA.ESP Project)
 * 
 */
public class SizeUtil {

	static public enum Unit {

		B(0), K(1), M(2), G(3);

		private Unit(int level) {
			this.level = level;
		}

		public int CompareLevelTo(Unit other) {
			return level - other.level;
		}

		private int level = 0;
	}

	public static final Unit B = Enum.valueOf(Unit.class, "B");

	public static final Unit K = Enum.valueOf(Unit.class, "K");

	public static final Unit M = Enum.valueOf(Unit.class, "M");

	public static final Unit G = Enum.valueOf(Unit.class, "G");

	public static String convert(long size, int base, Unit objectUnit) {
		double lv = Math.pow(base, objectUnit.level);

		return MessageFormat.format("{1,number,#,##0.###}{0}",
				objectUnit.toString(), size * 1.0 / lv);
	}

	public static long convert(String origin, int base, Unit objectUnit)
			throws Exception {

		if (base < 1) {
			throw new Exception("Error objectUnit values");
		}

		int length = origin.length();
		char u = origin.toUpperCase().charAt(length - 1);

		Unit originUnit = null;
		try {
			originUnit = Enum.valueOf(Unit.class, String.valueOf(u));
		} catch (Exception e) {
			throw new Exception("origin data unit is illegal");
		}

		int gap = originUnit.CompareLevelTo(objectUnit);

		double originData = 0;
		try {
			originData = Double.valueOf(origin.substring(0, length - 1));
		} catch (Exception e) {
			throw new Exception("origin data is illegal");
		}

		if (originData < 0) {
			throw new Exception("origin data can't lower than 0");
		}

		long result = (long) (originData * Math.pow(base, gap));

		return result;
	}

}
